package biznussoft.fieldservice360.fragments;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.MenuItemCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import biznussoft.fieldservice360.HomeActivity;
import biznussoft.fieldservice360.R;
import biznussoft.fieldservice360.adapter.AccountMasterAdapter;
import biznussoft.fieldservice360.listeners.GlobalListener;
import biznussoft.fieldservice360.model.Bean_Class;

import com.google.gson.Gson;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.util.EventsObservable;
import com.salesforce.androidsdk.util.EventsObservable.EventType;

public class AccountsFragment  extends BaseFragment implements OnItemClickListener, OnClickListener{
	private RestClient client;
	public static ArrayList<Bean_Class> list;
	private GlobalListener mHomeItemListener;        
	private ListView lv;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.listfragment, null);                  
	}         

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setHasOptionsMenu(true);

	}
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// TODO Auto-generated method stub
		super.onCreateOptionsMenu(menu, inflater);

        MenuItem addAccount = menu.add("Account");
        MenuItemCompat.setShowAsAction(addAccount, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
        addAccount.setIcon(R.drawable.add); 
       MenuItem actionItem = menu.add("Logout");                 
        MenuItemCompat.setShowAsAction(actionItem,MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT);
        actionItem.setIcon(R.drawable.logout); 
      
	}
 
 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
	 
	 if(item.getTitle().equals("Logout")){
		 SalesforceSDKManager.getInstance().logout(getActivity());}
	 if(item.getTitle().equals("Account")){
		
		 AccountsdetailsFragment newFragment = new AccountsdetailsFragment();
		 Bundle args = new Bundle();
		 args.putInt("Position", -1);
		 newFragment.setArguments(args);
		 FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
		 transaction.replace(R.id.viewer, newFragment);
		 transaction.addToBackStack(null);
		 transaction.commit();
	 }
	
	 return super.onOptionsItemSelected(item);
 }
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		mHomeItemListener = (GlobalListener) (activity);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		lv = (ListView) getView().findViewById(R.id.listview);
		lv.setOnItemClickListener(this);      
		client =  HomeActivity.mActivity.client;
		Bean_Class.api_Version = getString(R.string.api_version);

		Task task = new Task();
		task.execute();        

	}

	class Task extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			retriveLeads();
			return null;
		}

	}

	public void retriveLeads()        
	{
		try{
			String accounts = "Select Id,Name,AnnualRevenue,Fax,Phone,NumberOfEmployees,Ownership,Type,Industry,BillingCity,BillingState,BillingStreet,ShippingCity,ShippingCountry,ShippingPostalCode,ShippingState,ShippingStreet,BillingCountry,BillingPostalCode,Rating,Description,Website from Account";
			Log.i("TPT","SOQL is     :"+accounts);


			RestRequest restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), accounts);

			client.sendAsync(restRequest, new AsyncRequestCallback() {  
				@Override
				public void onSuccess(RestRequest request, RestResponse result) {
					try {            
						Log.i("TPT","Response is   :"+result);
						JSONObject jsonObject1 = new JSONObject(result.asString());
						Log.i("NCS","jsonobject1  is  :"+jsonObject1.length());

						JSONArray jsonArray = jsonObject1.getJSONArray("records");
						Log.i("RGT","jsonArray  is  :"+jsonArray.length());

						list = new ArrayList<Bean_Class>();
						Gson _gson = new Gson();
						for(int i=0; i< jsonArray.length(); i++)
						{
							if(!jsonArray.isNull(i)){
								Bean_Class bean = _gson.fromJson(jsonArray.getString(i), Bean_Class.class);
								list.add(bean);
							}
						}

						showRecords();

					} catch (Exception e) {
						onError(e);
					}
				}

				@Override
				public void onError(Exception exception) {
					EventsObservable.get().notifyEvent(EventType.RenditionComplete);
				}
			});



		} catch (Exception e) {
			Log.i("NCS","Exception  2 is  :"+e.getMessage());
		}

	}


	public void showRecords(){
		AccountMasterAdapter adapter = new AccountMasterAdapter(getActivity(),list);
		lv.setAdapter(adapter);
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		 setHasOptionsMenu(false);
		mHomeItemListener.onCategoryClicked(position);
	}

	public void onClick(View arg0) {
		mHomeItemListener.onCategoryClicked(-1);                     

	}
}

